import time
from functools import wraps

from utils.context.utils.out import context_append, context_get, context_set, clear_context


def context_def_time(remark=''):
    """
        工具1： 统计函数执行时间
        remark: 统计备注
    """
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            start_time = time.perf_counter()  # 更高精度的时间函数
            response = func(*args, **kwargs)
            end_time = time.perf_counter()

            data = {
                'func_name': func.__name__,
                'remark': remark,
                'start_time': start_time,
                'end_time': end_time,
                'count': 1,
                'cost_time': end_time - start_time
            }
            flag = False
            _data = context_get('exec_time')
            if _data is not None:
                for each in _data:
                    if each['func_name'] == data['func_name']:
                        each['cost_time'] += data['cost_time']
                        each['count'] += 1
                        flag = True
                        break
            if not flag:
                context_append('exec_time', data)
            else:
                context_set('exec_time', _data)  # 更新现有的 _data 列表
            return response
        return wrapper
    return decorator
